package com.tanhua.sso.service.impl;



import cn.hutool.core.util.StrUtil;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.MyCenterService;
import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class MyCenterServiceImpl implements MyCenterService {

    @Autowired
    private UserService userService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 修改手机号发送短信验证码
     *
     * @param token
     * @return
     */
    @Override
    public Boolean sendVerificationCode(String token) {
        //校验token
        User user = this.userService.queryUserByToken(token);

        if (!Optional.ofNullable(user).isPresent()){
            return false;
        }

        ErrorResult errorResult = this.smsService.sendCheckCode(user.getMobile());

        return errorResult == null;
    }

    /**
     * 修改手机号验证短信验证码
     * @param token
     * @param verificationCode
     * @return
     */
    @Override
    public Boolean checkVerificationCode(String token, String verificationCode) {
        //校验token
        User user = this.userService.queryUserByToken(token);

        if (!Optional.ofNullable(user).isPresent()){
            return false;
        }
        //校验验证码，先查询redis中的验证码
        String redisKey = "CHECK_CODE_" + user.getMobile();
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (StrUtil.equals(verificationCode, value)){
            //将验证码删除
            this.redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }

    /**
     * 保存新手机号
     * @param token
     * @param newPhone
     * @return
     */
    @Override
    public Boolean saveNewPhone(String token, String newPhone) {
        //校验token
        User user = this.userService.queryUserByToken(token);
        if (!Optional.ofNullable(user).isPresent()){
            return false;
        }

        Boolean result = this.userService.updatePhone(user.getId(), newPhone);

        if (result){
            //删除原来在Redis中的电话号码
            String redisKey = "TANHUA_USER_MOBILE_" + user.getMobile();
            this.redisTemplate.delete(redisKey);
        }
        return result;
    }
}
